<template>
  <div class="beam-layout-container">
    <!-- 顶部查询条件 -->
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <!-- 下发状态 -->
          <bjSelect
            :allowClear="true"
            placeholder="请选择下发状态"
            :dataResource="stateSource"
            v-model="state"
            @change="conditionChange($event, 'state')"
          >
          </bjSelect>
          <!-- 所属桥梁 -->
          <bjSelect
            :allowClear="true"
            :loading="bridgeNameLoading"
            placeholder="请选择所属桥梁"
            :replaceFields="bridgeNameReplaceFields"
            :dataResource="bridgeNameSource"
            v-model="bridgeName"
            @change="conditionChange($event, 'bridgeName')"
          >
          </bjSelect>
          <!-- 幅别 -->
          <bjSelect
            :allowClear="true"
            placeholder="请选择幅别"
            :dataResource="amClassSource"
            v-model="amClass"
            @change="conditionChange($event, 'amClass')"
          >
          </bjSelect>
          <!-- 梁类型 -->
          <bjSelect
            :allowClear="true"
            :loading="beamTypeLoading"
            placeholder="请选择梁类型"
            :replaceFields="beamTypeReplaceFields"
            :dataResource="beamTypeSource"
            v-model="beamType"
            @change="conditionChange($event, 'beamType')"
          >
          </bjSelect>
          <!-- 梁号 -->
          <a-input
            placeholder="请输入梁号"
            v-model="componentParts"
            allowClear
          />
          <!-- 时间 -->
          <bjRangeCalendar
            :format="dateFormat"
            v-model="dateRange"
            :show-time="{ format: dateFormat }"
            @ok="calendarOk"
            @change="calendarChange"
          ></bjRangeCalendar>
        </template>
        <template slot="operate">
          <a-button type="primary" @click="search()"> 查询 </a-button>
        </template>
      </ScreenConditions>
    </div>
    <div class="beam-table-container">
      <div class="table-header" header="一梁一码溯源管理">
        <a-button type="primary" @click="QRCodeDownload()">
          二维码下载
        </a-button>
      </div>
      <div class="main" v-loading="loading">
        <vxe-table
          ref="xTable"
          height="99%"
          class="scrollbarStyle"
          align="center"
          show-overflow
          show-header-overflow
          :data="tableData"
          @checkbox-all="onSelectAll"
          @checkbox-change="onSelect"
          :column-config="{ resizable: true }"
        >
          <vxe-column type="checkbox" width="60" fixed="left"></vxe-column>
          <vxe-column
            fixed="left"
            type="seq"
            width="80"
            title="序号"
          ></vxe-column>
          <vxe-column
            show-overflow
            :key="index"
            :title="item.title"
            :field="item.key"
            :min-width="item.width || 180"
            :fixed="item.fixed"
            v-for="(item, index) in columns"
          >
            <template #default="{ row }">
              <div v-if="item.key == 'actualStartTime'">
                {{ row.actualStartTime }}~{{ row.actualEndTime }}
              </div>
              <div v-else-if="item.key == 'actualJqStartTime'">
                {{ row.actualJqEndTime }}
              </div>
              <div
                v-else-if="item.key == 'taskNodeDesc'"
                class="item-node-text"
                :class="row.taskNodeDesc == '已完成' && 'complete'"
              >
                {{ row.taskNodeDesc || "--" }}
              </div>
              <div
                v-else-if="item.key == 'rectifyDate'"
                style="position: relative"
              >
                <img
                  @click="viewQrCode(row)"
                  class="code-img"
                  src="https://jszhgd.cn/static/pc/codeIcon.png"
                />
                <div class="download-code">
                  <vue-qr
                    :id="'qr' + row.id"
                    :text="row.qrCodePath"
                    :margin="0"
                    :size="300"
                    :autoColor="true"
                    :logoSrc="logo"
                    :logoScale="0.2"
                  >
                  </vue-qr>
                </div>
              </div>
              <div v-else>{{ row[item.key] }}</div>
            </template>
          </vxe-column>
          <vxe-column
            field="operate"
            width="220"
            title="操作"
            fixed="right"
            align="center"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <a-button
                  type="link"
                  v-if="row.lcxxflag"
                  @click="gotoProcessMonitoring(row)"
                >
                  流程监控
                </a-button>
                <a-button
                  type="link"
                  v-if="row.jqButton"
                  @click="gotoBridge(row)"
                >
                  出梁
                </a-button>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="pager-container">
        <vxe-pager
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump']"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              第<span>1</span>到<span
                >{{ Math.ceil(pager.total / pager.pageSize) || 1 }}页 </span
              >共<span>{{ pager.total }}</span
              >条记录
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
    <!-- 流程监控 -->
    <processPage :visible.sync="processVisible" :rows="row"></processPage>
    <!-- 二维码信息弹窗 -->
    <qrCodeModal :visible.sync="qrCodeVisible" :dataSource="row"></qrCodeModal>
    <!-- 出梁 -->
    <bridgeModal :visible.sync="bridgeVisible" :dataSource="row"></bridgeModal>
  </div>
</template>

<script>
import vueQr from "vue-qr";
import JSZip from "jszip";
import html2canvas from "html2canvas";
import { saveAs } from "file-saver";
import bjSelect from "@/components/bj-select";
import bjRangeCalendar from "@/components/bj-range-calendar";
import processPage from "./components/processMonitoring.vue";
import qrCodeModal from "./components/qrCodeModal.vue";
import bridgeModal from "./components/bridgeModal.vue";
import { getBridgeList } from "@/api/wisdom-beam/beamInfoConfig";
import { getDickeyList } from "@/api/common";
import { getTraceabilityList } from "@/api/wisdom-beam/quality-app";
import { getLoginData } from "@/tools";
import { chartString } from "@/utils";
export default {
  components: {
    vueQr,
    bjSelect,
    bjRangeCalendar,
    processPage,
    qrCodeModal,
    bridgeModal,
  },
  data() {
    return {
      row: {},
      //出梁
      bridgeVisible: false,
      //二维码信息弹窗
      qrCodeVisible: false,
      //流程监控
      processVisible: false,
      loading: false,
      columns: [
        {
          title: "桥梁名称",
          key: "bridgeName",
          fixed: "left",
        },
        {
          title: "幅别",
          key: "amClass",
          fixed: "left",
          width: 100,
        },
        {
          title: "跨",
          key: "span",
          fixed: "left",
          width: 100,
        },
        {
          title: "梁号",
          key: "componentParts",
          fixed: "left",
        },
        {
          title: "梁类型",
          key: "beamTypeDesc",
        },

        {
          title: "实际生产时间",
          key: "actualStartTime",
        },
        {
          title: "实际出梁时间",
          key: "actualJqStartTime",
        },
        {
          title: "当前节点",
          key: "taskNodeDesc",
        },
        {
          title: "二维码",
          key: "rectifyDate",
          fixed: "right",
          width: 120,
        },
      ],
      tableData: [],
      pager: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      //所属桥梁
      bridgeName: undefined,
      bridgeNameSource: [],
      bridgeNameLoading: false,
      bridgeNameReplaceFields: { key: "key", label: "value" },
      //所属幅别
      amClass: undefined,
      amClassSource: [
        {
          key: "左幅",
          value: "左幅",
        },
        {
          key: "右幅",
          value: "右幅",
        },
      ],
      //所属梁类型
      beamTypeLoading: false,
      beamType: undefined,
      beamTypeSource: [],
      beamTypeReplaceFields: { key: "dicValue", label: "dicDesc" },
      //梁号
      componentParts: "",
      //状态
      state: undefined,
      stateSource: [
        {
          key: "0",
          value: "未下发",
        },
        {
          key: "1",
          value: "待完成",
        },
        {
          key: "2",
          value: "已完成",
        },
        {
          key: "3",
          value: "已出梁",
        },
      ],
      //时间
      dateFormat: "YYYY-MM-DD HH:mm:ss",
      dateRange: [],
      choosedTableList: [],
      logo: "https://jszhgd.cn/static/pc/beamyard/qr_icon.jpg",
    };
  },
  mounted() {
    this.getBridgeList();
    this.getBeamType();
    this.getTableData();
  },
  methods: {
    //二维码下载
    QRCodeDownload() {
      let { choosedTableList } = this;
      if (choosedTableList.length == 0) {
        this.$message.warning("请选择您要下载的二维码！");
        return;
      }
      if (choosedTableList.length == 1) {
        let row = choosedTableList?.[0] ?? {};
        this.downloadQrCode(row);
      } else {
        this.downloadQrCodes(choosedTableList);
      }
    },
    //二维码-单张下载-图片
    async downloadQrCode(row = {}) {
      var htmlName = document.getElementById("qr" + row.id);
      const canvas = await html2canvas(htmlName);
      const dataUrl = canvas.toDataURL("image/png");
      const blob = await fetch(dataUrl).then((res) => res.blob());
      saveAs(blob, `${row.bridgeName}-${row.beamlocation}.png`);
    },
    //二维码-批量下载-压缩包
    async downloadQrCodes(data = []) {
      const zip = new JSZip();
      // 循环生成二维码并添加到压缩包;
      for (let i = 0; i < data.length; i++) {
        const row = data[i];
        var htmlName = document.getElementById("qr" + row.id);
        const canvas = await html2canvas(htmlName);
        const dataUrl = canvas.toDataURL("image/png");
        const blob = await fetch(dataUrl).then((res) => res.blob());
        zip.file(`${row.bridgeName}-${row.beamlocation}.png`, blob);
      }
      // 生成压缩包并下载
      zip.generateAsync({ type: "blob" }).then((content) => {
        saveAs(content, "一梁一码.zip");
      });
    },

    onSelectAll() {
      let selectRecords = this.$refs.xTable.getCheckboxRecords();
      this.choosedTableList = selectRecords;
    },

    onSelect() {
      let selectRecords = this.$refs.xTable.getCheckboxRecords();
      this.choosedTableList = selectRecords;
    },

    //查询桥梁列表
    getBridgeList() {
      this.bridgeNameLoading = true;
      return new Promise((resolve, reject) => {
        getBridgeList({})
          .then((res) => {
            let { data } = res;
            let list = data?.result || [];
            this.bridgeNameSource = list.map((v) => {
              return { key: v, value: v };
            });
            resolve();
          })
          .catch((_) => {
            this.bridgeNameSource = [];
            reject();
          })
          .finally((_) => {
            this.bridgeNameLoading = false;
          });
      });
    },

    //查询梁类型
    getBeamType() {
      this.beamTypeLoading = true;
      return new Promise((resolve, reject) => {
        getDickeyList({ dictKey: "TASK_MANAGER_TYPE" })
          .then((res) => {
            let { data } = res;
            this.beamTypeSource = data?.result ?? [];
            resolve();
          })
          .catch((_) => {
            this.beamTypeSource = [];
            reject();
          })
          .finally((_) => {
            this.beamTypeLoading = false;
          });
      });
    },

    //出梁
    gotoBridge(row) {
      this.row = row;
      this.bridgeVisible = true;
    },

    //二维码预览
    viewQrCode(item = {}) {
      this.row = item;
      this.qrCodeVisible = true;
    },

    //流程监控
    gotoProcessMonitoring(row) {
      this.row = row;
      this.processVisible = true;
    },

    //查询列表
    getTableData() {
      this.loading = true;
      this.choosedTableList = [];
      let { page, pageSize } = this.pager;
      let { componentParts, bridgeName, amClass, beamType, state, dateRange } =
        this;
      let { tenantCode, userId, sysSource } = getLoginData();
      return new Promise((resolve, reject) => {
        getTraceabilityList({
          page,
          pageSize,
          componentParts,
          completeStatus: state?.key,
          bridgeName: bridgeName?.key,
          amClass: amClass?.key,
          beamType: beamType?.key,
          startTime: dateRange?.[0],
          endTime: dateRange?.[1],
        })
          .then((res) => {
            let {
              data: { result },
            } = res;
            this.tableData = result?.rows || [];
            this.pager.total = result?.total || 0;
            this.tableData.forEach((item) => {
              let { qrCode } = item;
              let qrUrl =
                `http://lh.gzbsx.com:70/dashboard/h5/qr.html` +
                chartString({
                  qrCode,
                });
              this.$set(item, "qrCodePath", qrUrl);
            });
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    search() {
      this.pager.page = 1;
      this.getTableData();
    },

    //监听筛选条件切换
    conditionChange(ev, keyName) {
      this[keyName] = ev;
      this.search();
    },

    //监听日期选择
    calendarOk(dates = []) {
      this.dateRange = dates;
      this.search();
    },

    calendarChange(dates = []) {
      this.dateRange = dates;
      if (this.dateRange.length == 0) {
        this.search();
      }
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.choosedTableList = [];
      this.getTableData();
    },
  },
};
</script>

<style lang="less" scoped>
.code-img {
  width: 30px;
  height: 30px;
  margin: 0 auto;
  cursor: pointer;
}
.item-node-text {
  color: #0098ff;
  .flex();
  align-items: center;
  justify-content: center;
  &::before {
    content: "";
    display: block;
    width: 4px;
    height: 4px;
    background: #0098ff;
    border-radius: 50%;
    margin-right: 6px;
  }
  &.complete {
    color: #4bc964;
    &::before {
      background: #4bc964;
    }
  }
}

.download-code {
  width: 300px;
  height: 300px;
  position: absolute;
  opacity: 0;
}
</style>
